import React from 'react';
import classNames from 'classnames';
import { getSvgContent, ioniconContent } from './request';
import './Icon.less';

class Icon extends React.Component {
    displayName = 'Icon';

    static defaultProps = {
        size: 32,
        border: 1,
        color: 'currentColor',
        fill: 'none'
    }

    state = {
        svg: null,
        name: this.props.name
    }

    async componentDidMount () {
        const {name} = this.props;
        try {
            const {default: svg} = await import(`./svg/${name}.svg`);
            this.loadIcon(svg, name);
        } catch (e) {
            // todo
        }
    }

    loadIcon (url, name) {
        if (url) {
            if (ioniconContent.has(url)) {
                const svgContent = ioniconContent.get(url);
                this.setState({
                    name,
                    svg: svgContent
                }, () => {
                    this.refreshProps();
                });
            } else {
                getSvgContent(url).then(() => {
                    const svgContent = ioniconContent.get(url);
                    this.setState({
                        name,
                        svg: svgContent
                    }, () => {
                        this.refreshProps();
                    });
                });
            }
        }
    }

    refreshProps () {
        if (this.container) {
            const svg = this.container.querySelector('svg');
            svg.setAttribute('width', this.props.size);
            svg.setAttribute('height', this.props.size);
            svg.setAttribute('stroke', this.props.color);
            svg.setAttribute('stroke-width', 512 / this.props.size * this.props.border);
            svg.setAttribute('fill', this.props.fill);
        }
    }

    async componentDidUpdate () {
        if (this.props.name !== this.state.name) {
            try {
                const name = this.props.name;
                const {default: svg} = await import(`./svg/${name}.svg`);
                this.loadIcon(svg, name);
            } catch (e) {
                // todo
            }
        }
    }

    render () {
        let {className, style, name} = this.props;
        const clazzName = classNames(className, 'cm-icon', `cm-icon-${name}`);
        style = style || {};
        return <div onClick={this.props.onClick} ref={f => this.container = f} className={clazzName} style={style} dangerouslySetInnerHTML={{__html: this.state.svg}}></div>;
    }
}

export default Icon;
